import React, { Component} from "react";
import { Button, message, Steps } from "antd";
import {Link, withRouter} from "react-router-dom";
import Myselect from "../containers/myselect.js";
import ajax from "../ajaxMethod";
import moment from 'moment';

import '../assets/stylesheets/book.css';

class BookF extends Component{
    constructor(props){
        //只会在第一次的时候调用这个，刷新后不会调用
        super(props);
        this.state=JSON.parse(localStorage.getItem("valuesS"))?JSON.parse(localStorage.getItem("valuesS")):{
            initalValues:this.props.location.values?(()=>{
                localStorage.setItem("valueS", JSON.stringify(this.props.location.values));
                return this.props.location.values;
            })(): JSON.parse(localStorage.getItem("valueS")),
            values:{//这个刷新后就消失，不记录
                passenger:[{
                    type: "0",//0:成人，1:儿童，2:婴儿
                    name: "",
                    IDnumber: "",//用户身份证号码，若是child和baby用其他的
                    phone: "",//可以为空
                    pay:1,
                    construction: 1,//机建
                    fuel: 1,//燃油
                }],//乘客信息，可能是多个
                number: 1,//票数
                contact:{
                    phone:"",
                    email:"",
                },//联系人信息
            }
        }
    }
    componentDidMount(){
        
    }
    //添加乘客，默认是成人
    addPassengerClick = () =>{
        if(this.state.values.number < 4){
            this.setState({
                values:{...this.state.values, 
                    number: this.state.values.number + 1, 
                    passenger:(()=>{
                        let passenger = this.state.values.passenger;
                        passenger.push({
                            type: "0",
                            name: "",
                            IDnumber: "",
                            phone: "",
                            pay:1,
                            construction:1,
                            fuel:1,
                        })
                        return passenger;
                    })(),
                }
            });
        }else{
            message.warning("每个订单最多只能预订4人");
        }
    }
    //删除第i个乘客，不能小于一个人//有儿童票的航线标准价的50%，不收机建费，燃油费为成人的50%。//婴儿票按照航线标准价格的10%不收机建及燃油费
    subPassengerClick = (e) =>{
        let i = parseInt(e.target.getAttribute("data-num"));
        console.log("删除第i个",i);
        if(this.state.values.number > 1){
            this.setState({
                values:{...this.state.values, 
                    number: this.state.values.number - 1,
                    passenger:(()=>{
                        let passenger = this.state.values.passenger;
                        passenger.splice(i,1);
                        return passenger;
                    })(),
                }
            });
        }
    }
    //改变第i个乘客订票类型，//有儿童票的航线标准价的50%，不收机建费，燃油费为成人的50%。//婴儿票按照航线标准价格的10%不收机建及燃油费
    changeOption = (childprops, opt, value) => {//第i个用户的值改变了
        this.setState({
            values:{...this.state.values,
                passenger:(()=>{
                    let passenger = this.state.values.passenger;
                    passenger[childprops.dataNum].type = opt;
                    if(opt === "0"){ 
                        passenger[childprops.dataNum].pay = 1,
                        passenger[childprops.dataNum].construction = 1; 
                        passenger[childprops.dataNum].fuel = 1; 
                    }
                    if(opt === "1"){//儿童
                        passenger[childprops.dataNum].pay = 0.5,
                        passenger[childprops.dataNum].construction = 0; 
                        passenger[childprops.dataNum].fuel = 0.5; 
                    }
                    if(opt === "2"){//婴儿
                        passenger[childprops.dataNum].pay = 0.1,
                        passenger[childprops.dataNum].construction = 0; 
                        passenger[childprops.dataNum].fuel = 0; 
                    }
                    return passenger;
                })(),
            }
        });
    }
    //第i个乘客姓名改变
    usernameChange = (e) =>{
        let i = parseInt(e.target.getAttribute("data-num"));
        this.setState({values:{...this.state.values,
            passenger:(()=>{
                let passenger = this.state.values.passenger;
                passenger[i].name = e.target.value;
                return passenger;
            })(),
        }});
    }
    //第i个乘客登机证件号改变
    userIDChange = (e) =>{
        let i = parseInt(e.target.getAttribute("data-num"));
        this.setState({values:{...this.state.values,
            passenger:(()=>{
                let passenger = this.state.values.passenger;
                passenger[i].IDnumber = e.target.value;
                return passenger;
            })()
        }});
    }
    //第i个乘客手机号改变
    userPhoneChange = (e) =>{
        let i = parseInt(e.target.getAttribute("data-num"));
        this.setState({values:{...this.state.values,
            passenger:(()=>{
                let passenger = this.state.values.passenger;
                passenger[i].phone = e.target.value;
                return passenger;
            })()
        }});
    }
    contactPhone = (e) =>{
        this.setState({values:{...this.state.values,
            contact:{...this.state.values.contact, phone:e.target.value}
        }});
    }
    contactEmail = (e) =>{
        this.setState({values:{...this.state.values,
            contact:{...this.state.values.contact, email:e.target.value}
        }});
    }
    onSubmit = (e) => {
        let state = 0,
            babyFlag = false,
            adultFlag = false,
            passenger = this.state.values.passenger,
            kongExp = /\s/g,
            phoneExp = /^1[34578]\d{9}$/,
            _this = this;
        //所有用户都填完了才提交，状态为以下
        //0:ok, 1：姓名有没填的， 2：登机证件号有没填的，3：联系人手机号格式不正确，4有婴儿，但是没有成人, 5同一乘客不能预定多张机票
        if(!phoneExp.test(this.state.values.contact.phone)){ state = 3; }
        for(let i = 0; i < passenger.length; i++){
            passenger[i].name = passenger[i].name.replace(kongExp,"");
            if(passenger[i].name === ""){
                state = 1;break;
            }
            passenger[i].IDnumber = passenger[i].IDnumber.replace(kongExp,"");
            if(passenger[i].IDnumber === ""){
                state = 2; break;
            }
            if(passenger[i].type === "0"){ adultFlag = true;}
            if(passenger[i].type === "2"){ babyFlag = true;}
        }
        if(babyFlag && !adultFlag){ state = 4; }
        for(let i = 0; i < passenger.length; i++){
            passenger[i].name 
            for(let j = i + 1; j < passenger.length; j++){
                if(passenger[i].name === passenger[j]. name){//使用身份证编号检测
                    state = 5; break;
                }
            }
        }
        switch(state){
            case 0:{//成功
                ajax.postAjax("/interface/travelTest", this.state, res =>{
                    if(res.success){
                        if(res.data.state === 1){
                            message.error("有乘客行程冲突，请重新选择行程");
                        }else{
                            _this.props.history.push({pathname:"/bookSecond", values:this.state});
                        }
                    }else{
                        message.error(res.description);
                        console.error(res.description);
                    }
                }, err=>{
                    console.error(err);
                })
            }break;
            case 1:{ message.error("乘客姓名不能为空"); }break;
            case 2:{ message.error("登机证件不能为空"); }break;
            case 3:{ message.error("联系人手机号格式不正确"); }break;
            case 4:{ message.error("婴儿需在成人陪同下登机"); }break;
            case 5:{ message.error("同一乘客不能预定多张机票"); }break;
            default:{}
        }
    }
    render(){
        // 获取session/local？， E:1-7
        const initalValues = this.state.initalValues;
        const values = this.state.values;
        let typeobj = {},
            toTypeobj ={},
            sumPay = 0,
            sumConstruction = 0,
            sumFule = 0,
            sumGoTrip = 0,//去程总的钱
            sumToTrip = 0,//返程总的钱
            type="",
            toType="",
            typeValue = "",
            toTypeValue = "";
        switch(initalValues.goType){
            case "0":{
                typeValue="经济舱";
                type = "economyClass";
            };break;
            case "1":{
                typeValue="商务舱";
                type = "businessClass";
            };break;
            case "2":{
                typeValue="头等舱";
                type = "firstClass";
            };break;
            default:
        }
        typeobj =  initalValues.goTrip[type];
        for(let i = 0; i <  values.passenger.length; i++){
            sumPay += values.passenger[i].pay;
            sumConstruction += values.passenger[i].construction;
            sumFule += values.passenger[i].fuel;
        }
        sumGoTrip = sumPay * typeobj.afterPrice + sumConstruction * typeobj.construction + sumFule * typeobj.fuel;

        if(Object.keys(initalValues.toTrip).length){
            switch(initalValues.toType){
                case "0":{
                    toTypeValue="经济舱";
                    toType = "economyClass";
                };break;
                case "1":{
                    toTypeValue="商务舱";
                    toType = "businessClass";
                };break;
                case "2":{
                    toTypeValue="头等舱";
                    toType = "firstClass";
                };break;
                default:
            }
            toTypeobj =  initalValues.toTrip[toType];
            sumToTrip = sumPay * toTypeobj.afterPrice + sumConstruction * toTypeobj.construction + sumFule * toTypeobj.fuel;
        }
        console.log("book-f-state--------------------------",this.state);
        return(
        <div id="book">
            <div className="top">
                <div>
                    <div><Link to="/"><i className="logo"></i></Link></div>
                    <div className="step">
                        <Steps current={0} size="small">
                            <Steps.Step title="乘机信息" description="" />
                            <Steps.Step title="确认信息" description="" />
                            <Steps.Step title="支付" description="" />
                            <Steps.Step title="完成" description="" />
                        </Steps>
                    </div>
                </div>
            </div>
            <div className="content">
                <div className="left">
                    <div className="tips">
                        <p><i>i</i><span>该航班预计最晚于起飞前72小时完成出票，保障出行</span></p>
                        <p><i>i</i><span>每个订单最多只能预定4位乘客</span></p>
                        {(()=>{
                            if(!initalValues.goTrip.flight.child && !initalValues.goTrip.flight.baby){
                                return <p><i>i</i>您预订的产品仅限预订成人票</p>
                            }else if(initalValues.goTrip.flight.baby){
                                return <p><i>i</i>婴儿只能与成人预定同一航班,且需在成人带领下登机</p>
                            }
                        })()}
                    </div>
                    <div className="passenger">
                        <h2>乘客</h2>
                        <div>
                            {(()=>{
                                let i = 0,
                                    passenger = [];
                                console.log("values.passenger[i].", values.passenger[i]);
                                for(;i < values.number; i++){
                                    passenger.push(<form>
                                        <div className="inputs">
                                            <Myselect onChange={this.changeOption}
                                                dataNum={i}
                                                value={values.passenger[i].type}
                                                values={{"0":"成人","1":"儿童","2":"婴儿"}}>
                                            </Myselect>
                                            <input className="name" data-num={i} onChange={this.usernameChange} placeholder="姓名,请与登机证件姓名一致" maxLength="32" value={values.passenger[i].name}></input>
                                            <input data-num={i} className="id-number" onChange={this.userIDChange} placeholder="登机证件号码" maxLength="32" value={values.passenger[i].IDnumber}></input>
                                            <input data-num={i} onChange={this.userPhoneChange} placeholder="乘机人手机号码" maxLength="32" value={values.passenger[i].phone}></input>
                                        </div>
                                        <div className="opt">
                                            <div className="delete-box"> 
                                                <span>×</span><span className="delete" data-num={i} onClick={this.subPassengerClick}>删除</span>
                                            </div>
                                        </div>
                                        <i>{i+1}</i>
                                    </form>)
                                }
                                return passenger;
                            })()}
                        </div>
                        <Button onClick={this.addPassengerClick}>+ 添加乘客</Button>
                    </div>
                    <div className="contact">
                        <h2>联系人</h2>
                        <div className="inputs">
                            <input className="phone" placeholder="手机号,接收航变信息" onChange={this.contactPhone} value={values.contact.phone} maxLength="32"/>
                            <input className="email" placeholder="Email(选填,接收航变信息)" onChange={this.contactEmail} value={values.contact.email} maxLength="32"/>
                        </div>
                    </div>
                    <Button onClick={this.onSubmit} type="submit">下一步</Button>
                </div>
                <div className="right">
                    <div className="go-trip all-trip">
                        <div className="where">
                            <span className="trip">去</span>
                            <span>{moment(initalValues.goTrip.start.time).format("MM-DD")}</span>
                            
                            <span>周{(()=>{
                                let week = "一";
                                switch(moment(initalValues.goTrip.start.time).format("E")){
                                    case "2":week = "二"; break;
                                    case "3":week = "三"; break;
                                    case "4":week = "四"; break;
                                    case "5":week = "五"; break;
                                    case "6":week = "六"; break;
                                    case "7":week = "日"; break;
                                    default: ;
                                }
                                return week;
                            })()}</span>
                            <span>{initalValues.goTrip.start.city}</span>
                            <span>-</span>
                            <span>{initalValues.goTrip.end.city}</span>
                        </div>
                        <div className="plain">
                            <span>{initalValues.goTrip.flight.company}</span>
                            <span>
                                {(()=>{
                                    let type = "小型";
                                    switch(initalValues.goTrip.flight.type){
                                        case 1:type = "中型";break;
                                        case 2:type = "大型";break;
                                        case 3:type = "巨型";break;
                                    }
                                    return initalValues.goTrip.flight.plane + "(" + type + "机)";
                                })()}
                            </span>
                            <span>{typeValue}</span>
                        </div>
                        {
                            (()=>{
                                let time = (moment(initalValues.goTrip.end.time).valueOf() - moment(initalValues.goTrip.start.time).valueOf())/1000;//秒
                                return <div className="when">
                                    <span>{moment(new Date(initalValues.goTrip.start.time)).format("HH:mm")}</span>
                                    <span className="over-time">{Math.floor(time / 3600)}h{parseInt(time % 3600 / 60)}m</span>
                                    <span>{moment(new Date(initalValues.goTrip.end.time)).format("HH:mm")}</span>
                                </div>
                            })()
                        }
                        <div className="location">
                            <span>{initalValues.goTrip.start.airport}</span>
                            <span>--------</span>
                            <span>{initalValues.goTrip.end.airport}</span>
                        </div>
                    </div>
                    {
                        (()=>{
                            // 返回的路程
                            if(Object.keys(initalValues.toTrip).length){
                                return <div div className="to-trip all-trip">
                                    <div className="where">
                                        <span className="trip">返</span>
                                        <span>{moment(initalValues.toTrip.start.time).format("MM-DD")}</span>
                                        <span>周{(()=>{
                                            let week = "一";
                                            switch(moment(initalValues.toTrip.start.time).format("E")){
                                                case "2":week = "二"; break;
                                                case "3":week = "三"; break;
                                                case "4":week = "四"; break;
                                                case "5":week = "五"; break;
                                                case "6":week = "六"; break;
                                                case "7":week = "日"; break;
                                                default: ;
                                            }
                                            return week;
                                        })()}</span>
                                        <span>{initalValues.toTrip.start.city}</span>
                                        <span>-</span>
                                        <span>{initalValues.toTrip.end.city}</span>
                                    </div>
                                    <div className="plain">
                                        <span>{initalValues.toTrip.flight.company}</span>
                                        <span>
                                            {(()=>{
                                                let type = "小型";
                                                switch(initalValues.toTrip.flight.type){
                                                    case 1:type = "中型";break;
                                                    case 2:type = "大型";break;
                                                    case 3:type = "巨型";break;
                                                }
                                                return initalValues.toTrip.flight.plane + "(" + type + "机)";
                                            })()}
                                        </span>
                                        <span>{toTypeValue}</span>
                                    </div>
                                    {
                                        (()=>{
                                            let time = (moment(initalValues.toTrip.end.time).valueOf() - moment(initalValues.toTrip.start.time).valueOf())/1000;//秒
                                            return <div className="when">
                                                <span>{moment(new Date(initalValues.toTrip.start.time)).format("HH:mm")}</span>
                                                <span className="over-time">{Math.floor(time / 3600)}h{parseInt(time % 3600 / 60)}m</span>
                                                <span>{moment(new Date(initalValues.toTrip.end.time)).format("HH:mm")}</span>
                                            </div>
                                        })()
                                    }
                                    <div className="location">
                                        <span>{initalValues.toTrip.start.airport}</span>
                                        <span>--------</span>
                                        <span>{initalValues.toTrip.end.airport}</span>
                                    </div>
                                </div>
                            }
                        })()
                    }
                    {
                        (()=>{
                            return Object.keys(initalValues.toTrip).length?
                            <div className="other-pay">
                                <div>
                                    <span className="repent">去程退改￥{initalValues.goTrip[type].repent}</span>
                                    <span className="luggage">行李额{initalValues.goTrip[type].luggage}KG</span>
                                    <sapn className="afterPrice price">￥{initalValues.goTrip[type].afterPrice}<span>x {sumPay}</span></sapn>
                                </div>
                                <div>
                                    <span className="repent">返程退改￥{initalValues.toTrip[toType].repent}</span>
                                    <span className="luggage">行李额{initalValues.toTrip[toType].luggage}KG</span>
                                    <sapn className="afterPrice price">￥{initalValues.toTrip[toType].afterPrice}<span>x {sumPay}</span></sapn>
                                </div>
                                <div>
                                    <span className="construction">机建</span>
                                    <sapn className="price">￥{initalValues.goTrip[type].construction+initalValues.toTrip[toType].construction} <span>x {sumConstruction}</span></sapn>
                                </div>
                                <div>
                                    <span className="fuel">燃油</span>
                                    <sapn className="price">￥{initalValues.goTrip[type].fuel + initalValues.goTrip[type].fuel} <span>x {sumFule}</span></sapn>
                                </div>
                            </div>:
                            <div className="other-pay">
                                <div>
                                    <span className="repent">去程退改￥{initalValues.goTrip[type].repent}</span>
                                    <span className="luggage">行李额{initalValues.goTrip[type].luggage}KG</span>
                                    <sapn className="afterPrice price">￥{initalValues.goTrip[type].afterPrice}<span>x {sumPay}</span></sapn>
                                </div>
                                <div>
                                    <span className="construction">机建</span>
                                    <sapn className="price">￥{initalValues.goTrip[type].construction} <span>x {sumConstruction}</span></sapn>
                                </div>
                                <div>
                                    <span className="fuel">燃油</span>
                                    <sapn className="price">￥{initalValues.goTrip[type].fuel} <span>x {sumFule}</span></sapn>
                                </div>
                            </div>
                        })()
                    }
                    <p><span>￥</span>{Object.keys(initalValues.toTrip).length?(sumGoTrip + sumToTrip).toFixed(2):(sumGoTrip).toFixed(2)}</p>
                </div>
            </div>
        </div>);
    }
}

export default withRouter(BookF);